package com.msb.servlet;

import com.msb.entity.Cpi;
import com.msb.mapper.Mapper;
import com.msb.unitil.DBUnitil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @version : 1.0
 * @Author: yangmingsong
 * @Date: 2021/2/7-02-07-23:20
 * @Description: demon
 */
@WebServlet(urlPatterns = "/Dosearch")
public class Dosearch extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1、设置返回值类型及字符编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/json; charset=utf-8");
        //2、获取表单数据
        String dataType = request.getParameter("dataType");
        String area = request.getParameter("area");
        String date = request.getParameter("date");
        System.out.println(dataType+"???");
        System.out.println(area+"?????");
        System.out.println(date+"?????");
        //3、数据校验
        if(dataType == null || dataType.length() < 0){
            request.setAttribute("msg","数据类型有误");
            return;
        }
        if(area == null || area.length() < 0){
            request.setAttribute("msg","数据类型有误");
            return;
        }
        if(date == null || date.length() < 0){
            request.setAttribute("msg","数据类型有误");
            return;
        }
        //4、调用DBUtils添加方法
        Mapper mapper = DBUnitil.getsqlsession().getMapper(Mapper.class);
        List<Cpi> rs = mapper.selectMore(dataType, area, date);
        DBUnitil.getsqlsession().close();
        //5、处理返回结果
        if(rs != null){
            //创建流对象
            PrintWriter write = response.getWriter();
            //创建大json对象
            JSONObject objMax = new JSONObject();
            //创建JSON数组
            JSONArray array = new JSONArray();
            for(Cpi cpi:rs){
                //创建小json对象
                JSONObject objMin = new JSONObject();
                //向json对象封装数据
                objMin.put("name", cpi.getGoodsName());
                objMin.put("value", cpi.getDate());
                //把json对象添加到json数组
                array.add(objMin);
            }
            //把json数据封装到json对象
            objMax.put("data_pie", array);
            //向浏览器客户端输出
            write.print(objMax);
            //清空缓存区
            write.flush();
        }
    }
}
